import TauPage from '@/components/TauPage';
import { useStore } from '@/hooks';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef } from 'react';
import { toJS } from 'mobx';
import moment from 'moment';
import Style from './ChatMessages.module.scss'; // 引入自定义样式
import { Avatar, Box } from '@alifd/next';

const baseUrl = 'https://apis.map.qq.com/tools/poimarker?type=0&key=5M6BZ-GS2KJ-SOLFY-FCORA-7Q34E-STF6C&referer=travel_uat';

const Order = ({ modal }) => {
  const { show: __, record } = modal;
  const { orderNumber } = record || {};
  const { orderStore: store } = useStore();
  const itemsRef = useRef(null);

  useEffect(() => {
    (async () => {
      const res = await store.getRooms({ bizKey: orderNumber });
      if (res) {
        // eslint-disable-next-line require-atomic-updates
        store.search_chat = {
          timeFrom: '',
          timeTo: '',
          from: '',
          withName: true,
          to: res?.id || '',
          type: 'groupchat',
          scope: 'cbv-driver-group',
        };
      }
    })();
    return () => {
      itemsRef.current = null;
      store.data_chat = [];
    };
  }, []);

  const handleViewImage = (e) => {
    const { src } = e.target;
    window.open(src);
  };

  function returnMessageTypes(params) {
    if (params?.x && params.x.length > 0) {
      const { src, meta, address, addressDesc } = params.x[0];
      const { width, height, name, latitude, longitude, ...types } = meta || {};
      switch (params.body) {
        case '[file]':
          return <a href={src} download>{name}</a>;
        case '[image]':
          return (
            <img
              style={{ maxWidth: '100%', maxHeight: '200px', cursor: 'pointer' }}
              src={params.x[0].src}
              onClick={handleViewImage}
            />
          );
        case '[voice]':
          return <audio src={src} style={{ width, height }} {...types} controls />;
        case '[video]':
          return <video src={src} style={{ width: width / 2, height: height / 2 }} {...types} controls />;
        case '[location]':
          return <iframe id="mapPage" title="map" width="100%" style={{ border: 0, height: 400 }} src={`${baseUrl}&marker=coord:${latitude},${longitude};title:${address};addr:${addressDesc}`} />;
        default:
          break;
      }
    } else {
      return <span>{params.body}</span>;
    }
  }

  return (
    <TauPage className="page-container">
      <Box justify="center" align="center">
        <div className={Style.center}>
          {toJS(store.data_chat).map((message) => {
            return (
              <div key={message.id} className={`message ${message.from === record?.username ? 'right' : 'left'}`}>
                <div className={'content'}>
                  {message.from === record?.username ? (
                    <>
                      <div className={'message_bubble'}>
                        {message?.x && message.x.length > 0 ? returnMessageTypes(message) : message.body}
                      </div>
                      <div className={'message_header'}>
                        <Avatar size="small" icon={'account'} alt={t`用户头像`} />
                        <span className={'from_name'}>{message.fromName}</span>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className={'message_header'}>
                        <Avatar size="small" icon={'account'} alt={t`用户头像`} />
                        <span className={'from_name'}>{message.fromName}</span>
                      </div>
                      <div className={'message_bubble'}>
                        {message?.x && message.x.length > 0 ? returnMessageTypes(message) : message.body}
                      </div>
                    </>
                  )}
                </div>
                <div className={'message_time'}>{moment(message.ts).format('HH:mm')}</div>
              </div>
            );
          })}
        </div>
      </Box>
    </TauPage>
  );
};

export default observer(Order);
